package com.shy.configs.common.exceptions;

import com.shy.configs.common.enums.RCode;
import com.shy.configs.mvc.models.AjaxResult;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
public class GlobalException extends RuntimeException {

    @ExceptionHandler(value={BindException.class})
    public AjaxResult d1oBeanValidationException(BindException be) {
        StringBuilder builder = new StringBuilder();
        List<FieldError> fieldErrors = be.getFieldErrors();
        fieldErrors.forEach(fl->{
            //String field = fl.getField();// 发生错误的字段名
            String defaultMessage = fl.getDefaultMessage();// 错误提示信息
            //builder.append("错误项目:[").append(field).append("],错误原因:[").append(defaultMessage).append("];");
            builder.append("错误原因:[").append(defaultMessage).append("];");
        });
        return new AjaxResult(RCode.REQUEST_PARAM_ERROR.getCode(), builder.toString(),"");
    }

    @ExceptionHandler(value = {DftException.class})
    public AjaxResult doBossException(DftException e){
        return AjaxResult.fail(e.getRCode());
    }
}
